import React, { useState, useEffect, useContext, useMemo } from 'react';
import { Table, message, Space, Input, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import LittleHeader from '../../components/LittleHeader';
import withAuth from '../../components/WithAuth';
import MainLayout from '../../components/MainLayout';
import { AuthContext } from '../../contexts/AuthContext';
import { useTranslation } from 'react-i18next';

const { Search } = Input;

const PublicBugs = () => {
    const [tableData, setTableData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 20,
        total: 553171,
    });
    const [searchValue, setSearchValue] = useState('');
    const navigate = useNavigate();
    const { token } = useContext(AuthContext);
    const { t } = useTranslation();

    useEffect(() => {
        if (token) {
            fetchData();
        }
    }, [pagination.current, pagination.pageSize, token]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const page = Math.max(pagination.current, 0);
            const data = {
                page: page,
                size: pagination.pageSize,
            };
            const response = await axios.post('/api/v1/vulnerability/query', data, {
                headers: {
                    'Authorization': token,
                }
            });
            console.log(response);
            if (response.data.code === 0) {
                const responseData = response.data?.data;
                const processedData = Array.isArray(responseData)
                    ? responseData.map(item => ({
                        key: item.id,
                        id: item.id,
                        assigner: item.assigner?.join(', ') || '未知',
                        description: item.description || '暂无描述',
                        severity: getSeverityLevel(item.severities?.[0]?.rank),
                        cvss: item.severities?.[0]?.value?.vector || 'N/A',
                        version: item.severities?.[0]?.value?.version || 'N/A',
                        scheme: item.severities?.[0]?.scheme || 'N/A',
                        source: item.severities?.[0]?.source || 'N/A',
                        rank: item.severities?.[0]?.rank
                    }))
                    : []; // 如果不是数组返回空

                setTableData(processedData);
                if (response.data.totalElements !== undefined) {
                    setPagination(prev => ({
                        ...prev,
                        total: response.data.totalElements
                    }));
                } else if (response.data.totalPages !== undefined) {
                    setPagination(prev => ({
                        ...prev,
                        total: response.data.totalPages * pagination.pageSize
                    }));
                }
            }
            else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'))
                localStorage.removeItem('username');
                localStorage.removeItem('enc_token');
                localStorage.removeItem('privilege_level');
                navigate('/login');
            }
        } catch (err) {
            console.error('获取数据失败:', err);
            message.error(t('获取漏洞数据失败'));
        } finally {
            setLoading(false);
        }
    };

    const getSeverityLevel = (rank) => {
        switch (rank) {
            case 5:
                return '严重';
            case 4:
                return '高危';
            case 3:
                return '中危';
            case 2:
                return '低危';
            case 1:
                return '可忽略';
            default:
                return '未知';
        }
    };

    const filteredData = useMemo(() => {
        if (!searchValue) return tableData;
        return tableData.filter(item => {
            if (item.id) {
                return item.id.toLowerCase().includes(searchValue.toLowerCase());
            }
            return false;
        });
    }, [tableData, searchValue]);

    const onSearch = (value) => {
        setSearchValue(value);
        setPagination(prev => ({
            ...prev,
            current: 1
        }));
    };

    const columns = [
        {
            title: t('漏洞ID'),
            dataIndex: 'id',
            key: 'id',
            render: (text) => <a>{text}</a>,
            width: 150,
        },
        {
            title: t('提供者'),
            dataIndex: 'assigner',
            key: 'assigner',
            width: 200,
        },
        {
            title: t('严重程度'),
            dataIndex: 'severity',
            key: 'severity',
            width: 120,
            render: (severity) => {
                let color = '';
                switch (severity) {
                    case '严重':
                        color = '#FF0000';
                        break;
                    case '高危':
                        color = '#FF6600';
                        break;
                    case '中危':
                        color = '#FFCC00';
                        break;
                    case '低危':
                        color = '#00CC00';
                        break;
                    default:
                        color = 'rgb(184, 184, 184)';
                }
                return <span style={{ color }}>{severity}</span>;
            },
            sorter: (a, b) => {
                const severityOrder = { '严重': 4, '高危': 3, '中危': 2, '低危': 1 };
                return severityOrder[a.severity] - severityOrder[b.severity];
            },
        },
        {
            title: t('评测'),
            dataIndex: 'cvss',
            key: 'cvss',
            width: 200,
            render: (text, record) => (
                <Space direction="vertical" size={4}>
                    <div>
                        <Tag color={record.severity === '严重' ? 'red' :
                            record.severity === '高危' ? 'orange' :
                                record.severity === '中危' ? 'gold' : 'green'}>
                            {text}
                        </Tag>
                        <span>v{record.version}</span>
                    </div>
                    <div>
                        <Tag>Scheme: {record.scheme}</Tag>
                    </div>
                    <div>
                        <Tag>Source: {record.source}</Tag>
                    </div>
                </Space>
            ),
        },
        {
            title: t('描述'),
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
        },
    ];

    return (
        <MainLayout defaultSelectedKey="4">
            <LittleHeader title={t('公开漏洞库')} />
            <div style={{ marginTop: '30px' }}>
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 30 }}>
                    <Search
                        placeholder={t("输入漏洞ID搜索")}
                        allowClear
                        enterButton
                        style={{ width: 400 }}
                        onSearch={onSearch}
                        onChange={(e) => setSearchValue(e.target.value)}
                        value={searchValue}
                    />
                </div>

                <Table
                    columns={columns}
                    dataSource={filteredData}
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        pageSizeOptions: ['20'],
                        showTotal: (total) => t('共{{total}}条数据', { total }),
                        showQuickJumper: true,
                    }}
                    onChange={(newPagination) => {
                        setPagination({
                            ...newPagination,
                            current: newPagination.current,
                            pageSize: newPagination.pageSize
                        });
                    }}
                    scroll={{ x: 'max-content' }}
                    bordered
                    size="middle"
                />
            </div>
        </MainLayout>
    );
};

export default withAuth(PublicBugs);